#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const chokidar = require('chokidar');

/**
 * macOS 开发环境启动脚本
 * 负责启动渲染进程构建监听和 Electron 主进程
 */

const projectRoot = path.resolve(__dirname, '..');
const rendererDir = path.join(projectRoot, 'renderer');
const rendererDistDir = path.join(rendererDir, 'dist');
const mainEntry = path.join(projectRoot, 'dist-electron', 'app', 'main', 'index.js');

let electronProcess = null;
let rendererWatcher = null;
let isRestarting = false;

/**
 * 启动渲染进程构建监听
 */
function startRendererWatch() {
  console.log('🔨 启动渲染进程构建监听...');
  
  // 先执行一次构建
  const viteProcess = spawn('npm', ['run', 'build'], {
    cwd: rendererDir,
    stdio: 'inherit',
    shell: true
  });

  viteProcess.on('error', (error) => {
    console.error('❌ 渲染进程构建失败:', error);
    process.exit(1);
  });

  return viteProcess;
}

/**
 * 启动 Electron 主进程
 */
function startElectron() {
  if (electronProcess) {
    return electronProcess;
  }

  console.log('🚀 启动 Electron 主进程...');
  
  electronProcess = spawn('npx', ['electron', mainEntry], {
    cwd: projectRoot,
    stdio: 'inherit',
    shell: true,
    env: {
      ...process.env,
      NODE_ENV: 'development',
      ELECTRON_IS_DEV: '1'
    }
  });

  electronProcess.on('close', (code) => {
    console.log(`📱 Electron 进程退出，代码: ${code}`);
    electronProcess = null;
    
    if (!isRestarting) {
      process.exit(code);
    }
  });

  electronProcess.on('error', (error) => {
    console.error('❌ Electron 启动失败:', error);
    electronProcess = null;
  });

  return electronProcess;
}

/**
 * 重启 Electron 进程
 */
function restartElectron() {
  if (isRestarting) {
    return;
  }

  isRestarting = true;
  console.log('🔄 重启 Electron 进程...');

  if (electronProcess) {
    electronProcess.removeAllListeners();
    electronProcess.kill();
    electronProcess = null;
  }

  // 等待一段时间后重启
  setTimeout(() => {
    startElectron();
    isRestarting = false;
  }, 1000);
}

/**
 * 监听渲染进程构建产物变化
 */
function watchRendererDist() {
  if (!fs.existsSync(rendererDistDir)) {
    console.log('⏳ 等待渲染进程构建产物...');
    return;
  }

  console.log('👀 监听渲染进程构建产物变化...');
  
  rendererWatcher = chokidar.watch(rendererDistDir, {
    ignored: /node_modules/,
    persistent: true,
    ignoreInitial: true
  });

  rendererWatcher.on('change', (filePath) => {
    console.log(`📝 渲染进程文件变化: ${path.relative(projectRoot, filePath)}`);
    
    // 如果 Electron 进程已启动，发送重载信号
    if (electronProcess && !isRestarting) {
      // 这里可以通过 IPC 发送重载信号，或者简单重启进程
      restartElectron();
    }
  });

  rendererWatcher.on('add', (filePath) => {
    console.log(`➕ 渲染进程新增文件: ${path.relative(projectRoot, filePath)}`);
  });

  rendererWatcher.on('error', (error) => {
    console.error('❌ 文件监听错误:', error);
  });
}

/**
 * 监听主进程文件变化
 */
function watchMainProcess() {
  console.log('👀 监听主进程文件变化...');
  
  const mainWatcher = chokidar.watch([
    path.join(projectRoot, 'app', '**', '*.ts'),
    path.join(projectRoot, 'app', '**', '*.js'),
    path.join(projectRoot, 'core', '**', '*.ts'),
    path.join(projectRoot, 'core', '**', '*.js')
  ], {
    ignored: /node_modules/,
    persistent: true,
    ignoreInitial: true
  });

  mainWatcher.on('change', (filePath) => {
    console.log(`📝 主进程文件变化: ${path.relative(projectRoot, filePath)}`);
    restartElectron();
  });

  mainWatcher.on('error', (error) => {
    console.error('❌ 主进程文件监听错误:', error);
  });
}

/**
 * 清理资源
 */
function cleanup() {
  console.log('🧹 清理资源...');
  
  if (rendererWatcher) {
    rendererWatcher.close();
  }
  
  if (electronProcess) {
    electronProcess.kill();
  }
  
  process.exit(0);
}

/**
 * 主函数
 */
async function main() {
  console.log('🎯 启动 macOS 开发环境...');
  console.log(`📁 项目根目录: ${projectRoot}`);
  
  // 检查必要文件
  if (!fs.existsSync(mainEntry)) {
    console.error(`❌ 主进程入口文件不存在: ${mainEntry}`);
    process.exit(1);
  }

  // 启动渲染进程构建
  console.log('⏳ 开始渲染进程构建...');
  const viteProcess = startRendererWatch();
  
  // 等待构建完成
  viteProcess.on('close', (code) => {
    if (code === 0) {
      console.log('✅ 渲染进程构建完成');
      
      // 启动文件监听
      watchRendererDist();
      watchMainProcess();
      
      // 启动 Electron
      startElectron();
    } else {
      console.error('❌ 渲染进程构建失败');
      process.exit(1);
    }
  });

  // 处理进程退出
  process.on('SIGINT', cleanup);
  process.on('SIGTERM', cleanup);
  process.on('exit', cleanup);
}

// 启动开发环境
main().catch((error) => {
  console.error('❌ 启动失败:', error);
  process.exit(1);
});